import KoaRouter from 'koa-router'
import Config from '@/config/Config'
import verifyToken from '@/middlewares/verifyToken'
import { Models } from '@/common/typings/modle'
import { command } from '@/server/mysql'
import { Success } from '@/core/HttpException'
import { commandTotal, formatWhere, getOrderBy, getPaginationStr } from '@/common/utils/sql'
import { getResourceListByUserId } from '@/api/v1/system/resource/getListByUserId'
import { isAdmin } from '@/api/v1/system/role/isAdmin'
const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/resource`,
})
router.post('/list', verifyToken, async (ctx: Models.Ctx) => {
  const {
    label,
    uniqueProp,
    type,
    status = '1',
    parentUniqueProp,
    isPagination = false,
    pageSize = 20,
    offset = 0,
    orderField,
    orderDirection = 'ASC',
    onlyTotal = false,
  } = ctx.request.body as any
  const auth = ctx.auth
  let where = `WHERE 1=1 ${label ? `AND label LIKE '%${label}%'` : ``} ${
    uniqueProp ? `AND unique_prop LIKE '%${uniqueProp}%'` : ``
  } ${type ? `AND type = '${type}'` : ``} ${
    parentUniqueProp ? `AND parent_unique_prop LIKE '%${parentUniqueProp}%'` : ``
  } ${status ? `AND status = '${status}'` : ``}`
  where = formatWhere(where)
  let total = 0
  let paginationStr = ''
  if (isPagination) {
    total = await commandTotal({ tableName: 'system_resource', where })
    if (!onlyTotal) {
      paginationStr = getPaginationStr({ pageSize, offset })
    }
  }
  let list: any = []
  if (!onlyTotal) {
    // 根据orderField 和 orderDirection 进行排序
    const orderBy = getOrderBy({
      orderField,
      orderDirection,
      config: {
        defaultOrderFieldStr: 'sort_number',
        defaultOrderDirectionStr: 'ASC',
      },
    })
    list = (
      await command(
        `SELECT id, label, unique_prop, parent_unique_prop, type, status, sort_number FROM system_resource ${where} ${orderBy} ${paginationStr};`,
        true,
      )
    ).results
  }
  const ia = await isAdmin(ctx)
  console.log('是否为管理员：', ia)
  // 如果不是管理员查询，则需要用权限控制
  if (!ia) {
    const resourceList = await getResourceListByUserId(auth.id)
    list = list.filter((item: any) => {
      return resourceList.some((rItem) => rItem.id === item.id)
    })
  }
  throw new Success({
    data: list,
    total,
  })
})
export default router
